#include "fileworker.h"
#include <QFile>
#include <QTextStream>
#include <QThread>
#include <QDebug>

FileWorker::FileWorker(const QString &path, QObject *parent)
    : QObject(parent), m_filePath(path)
{
}

void FileWorker::startWork()
{
    QFile file(m_filePath);
    if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        emit errorOccurred(tr("无法创建文件：") + m_filePath);
        return;
    }

    QTextStream stream(&file);
    stream.setCodec("UTF-8");  // 设置编码防止乱码

    try
    {
        for(int i = 0; i < 100; ++i)
        {
            if(QThread::currentThread()->isInterruptionRequested())
                break;

            stream << QStringLiteral("你好，“文件”") << "\n";
            stream.flush();  // 确保每次写入立即刷新

            // 精确延时500ms
            QThread::msleep(500);

            emit progress(i + 1);
        }
    }
    catch (...)
    {
        emit errorOccurred(tr("写入文件时发生异常"));
    }

    file.close();
    emit finished();
}
